package com.bianmaba.examples.service.authorization.user;

import com.bianmaba.examples.bean.authorization.Role;
import com.bianmaba.examples.bean.authorization.User;
import com.bianmaba.spring.security.basic.configuration.BasicWebSecurityConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CustomUserDetailsService extends BasicWebSecurityConfiguration.BasicUserDetailsService {
    private static final Logger LOG = LoggerFactory.getLogger(CustomUserDetailsService.class);
    @Autowired
    private IUserService userService;

    public CustomUserDetailsService() {
        LOG.info("加载自定义UserDetailService：" + CustomUserDetailsService.class.getName());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if (user != null) {
            List<GrantedAuthority> grantedAuthorities = createGrantedAuthorities(user.getRoles());
            boolean enabled = user.getEnabled();
            boolean accountNonExpired = user.getAccountExpiringDate().getTime() > System.currentTimeMillis();
            boolean credentialsNonExpired = user.getCredentialsExpiringDate().getTime() > System.currentTimeMillis();
            boolean accountNonLocked = !user.getLocked();
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);
            return userDetails;
        }
        UserDetails userDetails = super.loadUserByUsername(username);
        return userDetails;
    }

    private List<GrantedAuthority> createGrantedAuthorities(List<Role> roles) {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(0);
        for (Role role : roles) {
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
        return grantedAuthorities;
    }
}
